package com.example.admin.goodnews.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.admin.goodnews.utils.GetCurrentTimeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 新闻分类数据库的管理者
 * Created by admin on 2016/10/13.
 */

public class MyDBManager {
    String time = GetCurrentTimeUtil.getCurrentTime();
    private MyDBHelper dbHelper;
    private SQLiteDatabase sqLiteDatabase;

    public MyDBManager(MyDBHelper dbHelper, SQLiteDatabase sqLiteDatabase) {
        this.dbHelper = dbHelper;
        this.sqLiteDatabase = sqLiteDatabase;
    }

    // 增加数据
    public void insertdata(String name) {
        sqLiteDatabase = dbHelper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("select * from newsclass where name = '"
                + name + "'", null);
        if (cursor.getCount() > 0) {
            sqLiteDatabase.delete("newsclass", "name = ?", new String[]{name});
        }
        sqLiteDatabase.execSQL("insert into newsclass (name,date) values('" + name + "'," + time + ")");
        sqLiteDatabase.close();
    }

    // 删除数据
    public void deletedata(String name) {
        sqLiteDatabase = dbHelper.getWritableDatabase();
        sqLiteDatabase.delete("newsclass", "name = ?", new String[]{name});
        sqLiteDatabase.close();
    }

    // 删除所有
    public void deleteall() {
        sqLiteDatabase = dbHelper.getWritableDatabase();
        sqLiteDatabase.delete("newsclass", null, null);
        sqLiteDatabase.close();
    }

    // 查询数据
    public List<String> querydata() {
        sqLiteDatabase = dbHelper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("select * from newsclass", null);
        List<String> datalist = new ArrayList<String>();
        while (cursor.moveToNext()) {
            datalist.add(cursor.getString(cursor.getColumnIndex("name")));
        }
        sqLiteDatabase.close();
        return datalist;
    }

}
